package com.nj9you.sdk.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.WindowManager;
import android.widget.TextView;

import com.nj9you.sdk.constant.Constants;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    /**
     * dp转px
     *
     * @param context
     * @param dp
     * @return
     */
    public static int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * px转dp
     *
     * @param context
     * @param px
     * @return
     */
    public static int px2dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    public static Bitmap readAssetsImage(Context context, String img) {
        try {
            AssetManager am = context.getAssets();
            InputStream is = am.open(img);
            Bitmap bmp = BitmapFactory.decodeStream(is);
            is.close();
            return bmp;
        } catch (Exception e) {
        }
        return null;
    }

    public static String getSign(Context context) {
        return getSign(context, context.getPackageName());
    }

    /**
     * 获取指定包名的应用签名MD5
     *
     * @param context
     * @param packageName
     * @return
     */
    public static String getSign(Context context, String packageName) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(packageName,
                            PackageManager.GET_SIGNATURES);
            Signature[] signs = packageInfo.signatures;
            Signature sign = signs[0];
            return byte2MD5(sign.toByteArray());
        } catch (Exception e) {
            // Log.d(Log.TAG, "error : " + e);
        }
        return null;
    }

    public static String byte2MD5(byte[] byteArray) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            Log.d(Log.TAG, "error : " + e);
            return "";
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = md5Bytes[i] & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            Log.d(Log.TAG, "error : " + e);
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = md5Bytes[i] & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static void putJson(JSONObject jobj, String key, Object value) {
        try {
            jobj.put(key, value);
        } catch (Exception e) {
        }
    }

    public static String getFileDir(Context context) {
        if (context == null) {
            return null;
        }
        File file = null;
        file = context.getExternalFilesDir("advfile");
        if (file == null) {
            file = new File(context.getFilesDir(), "advfile");
        }
        file.mkdirs();
        return file.getAbsolutePath();
    }

    public static String guessFile(Context context, String url, String fileName) {
        File downFile = new File(Utils.getFileDir(context), fileName);
        return downFile.getAbsolutePath();
    }

    public static Bitmap decodeBitmap(int w, int h, String imgPath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, options);
        // Log.d(Log.TAG, "w : " + options.outWidth + " , h : " + options.outHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(imgPath, options);
    }

    public static boolean canDecodeBitmap(String imgPath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, options);
        return options.outHeight > 0 && options.outWidth > 0;
    }

    public static boolean doRegularExpression(String reg, String str) {
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static String getLocalIp() {
        String addr = Constants.DEFAULT_LOC_ADDR;
        try {
            for (Enumeration<NetworkInterface> en =
                 NetworkInterface.getNetworkInterfaces();
                 en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr =
                     intf.getInetAddresses();
                     enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        addr = inetAddress.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            Log.e(Log.TAG, "获取本机IP出错 : " + e);
        }
        return addr;
    }

    public static String getCpuName() {
        try {
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            String[] array = text.split(":\\s+", 2);
            for (int i = 0; i < array.length; i++) {
            }
            br.close();
            return array[1];
        } catch (FileNotFoundException e) {
            Log.e(Log.TAG, "error : " + e);
        } catch (IOException e) {
            Log.e(Log.TAG, "error : " + e);
        }
        return null;
    }

    public static String getMaxCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim();
    }

    public static String getMinCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim();
    }

    public static String getCurCpuFreq() {
        String result = "N/A";
        try {
            FileReader fr = new FileReader(
                    "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            result = text.trim();
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Long getTotalMemory() {
        BufferedReader localBufferedReader;
        String str2 = null;
        long tempLong = 0l;
        try {
            FileReader fr = new FileReader("/proc/meminfo");
            localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            String[] array = str2.split("\\:", 2);
            String[] array2 = array[1].trim().split("k", 2);
            tempLong = Integer.parseInt(array2[0].trim()) * 1000;
            localBufferedReader.close();
        } catch (IOException e) {

        }
        return tempLong;
    }

    public static long[] getRomMemroy() {
        long[] romInfo = new long[2];
        // Total rom memory
        romInfo[0] = getTotalInternalMemorySize();
        // Available rom memory
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        romInfo[1] = blockSize * availableBlocks;
        return romInfo;
    }

    public static long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    public static String formatSize(long size) {
        String suffix = null;
        float fSize = 0;

        if (size >= 1024) {
            suffix = "KB";
            fSize = size / 1024;
            if (fSize >= 1024) {
                suffix = "MB";
                fSize /= 1024;
            }
            if (fSize >= 1024) {
                suffix = "GB";
                fSize /= 1024;
            }
        } else {
            fSize = size;
        }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
        StringBuilder resultBuffer = new StringBuilder(df.format(fSize));
        if (suffix != null)
            resultBuffer.append(suffix);
        return resultBuffer.toString();
    }

    public static String getNetworkType(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkinfo = connManager.getActiveNetworkInfo();
        String networkType = "";
        if (networkinfo != null) {
            networkType = networkinfo.getTypeName();
        }

        return networkType;
    }

    public static int getLayoutId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "layout",
                paramContext.getPackageName());
    }

    public static int getStringId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "string",
                paramContext.getPackageName());
    }

    public static int getDrawableId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString,
                "drawable", paramContext.getPackageName());
    }

    public static int getStyleId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "style",
                paramContext.getPackageName());
    }

    public static int getId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "id",
                paramContext.getPackageName());
    }

    public static int getColorId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "color",
                paramContext.getPackageName());
    }

    public static long getLong(Context context, String key) {
        return PreferenceManager.getDefaultSharedPreferences(context).getLong(key, 0);
    }

    public static void putLong(Context context, String key, long value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(key, value).commit();
    }

    /**
     * 随机生成订单
     *
     * @return
     */
    public static String generateOrderFor20Bit() {
        SimpleDateFormat sdf_yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
        Random RANDOM = new Random();
        StringBuilder sb = new StringBuilder(20);
        sb.append(sdf_yyyyMMddHHmmss.format(new Date()));
        sb.append(100000 + RANDOM.nextInt(900000));
        return sb.toString();
    }

    /**
     * 将单位分的金额转换成单位元的金额（315->3.15）
     *
     * @param fee 待转换的金额
     * @return String 已被转换的金额
     */
    public static String convertFenToYuan(String fee) {
        return String.valueOf(new BigDecimal(fee).divide(new BigDecimal("100"),
                2, BigDecimal.ROUND_HALF_UP));
    }

    /**
     * 判断应用是否已经安装
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    packageName, PackageManager.GET_PERMISSIONS);
            if (info != null) {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            // Log.d(Log.TAG, "error : " + e);
        }
        return false;
    }

    /**
     * @param activity
     * @return 判断当前手机是否是全屏
     */
    public static boolean isFullScreen(Activity activity) {
        try {
            int flag = activity.getWindow().getAttributes().flags;
            if ((flag & WindowManager.LayoutParams.FLAG_FULLSCREEN)
                    == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    public static void sendPayResult(Context context, int error, String desc, String callback) {
        Intent intent = new Intent(callback);
        intent.putExtra("RESULT_CODE", error);
        intent.putExtra("RESULT_DESC", desc);
        context.sendBroadcast(intent);
    }

    /**
     * 判断是否是全屏
     *
     * @return
     */
    public static boolean isFullScreen(Context context) {
        boolean fullscreen = false;
        if (context instanceof Activity) {
            fullscreen = Utils.isFullScreen((Activity) context);
        }
        return fullscreen;
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    public static String generateRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static int parseStringToInt(String str) {
        int result = 0;
        try {
            result = Integer.parseInt(str);
        } catch (Exception e){
            result = 0;
        }
        return result;
    }

    public static void copyAssets(Context context, String src, String dst) {
        try {
            InputStream is = context.getAssets().open(src);
            FileOutputStream fos = new FileOutputStream(dst);
            byte buf[] = new byte[4024];
            int read = 0;
            while((read = is.read(buf)) > 0) {
                fos.write(buf, 0, read);
            }
            fos.close();
            is.close();
        } catch (Exception e) {
        }
    }

    public static void showInstallActivity(Context context, String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static void highLightText(TextView textView, CharSequence content, CharSequence highLight) {
        highLightText(textView, content, highLight, Color.RED);
    }

    public static void highLightText(TextView textView, CharSequence content, CharSequence highLight, int color) {
        if (textView == null) {
            return;
        }
        if (TextUtils.isEmpty(highLight) || TextUtils.isEmpty(content)) {
            textView.setText(content);
            return;
        }
        if (!TextUtils.isEmpty(content)) {
            SpannableString span = new SpannableString(content);
            int start = content.toString().indexOf(highLight.toString());
            if (start > -1) {
                int end = start + highLight.length();
                span.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                textView.setText(span);
            } else {
                textView.setText(content);
            }
        }
    }

    public static String getMetaData(Context context, String name) {
        String value = null;
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (appInfo != null) {
                value = appInfo.metaData.get(name).toString();
            }
        } catch (Exception e) {
            Log.d(Log.TAG, "error : " + e);
        }
        return value;
    }
}
